package com.dhcc.DRGsHosp.facade.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.openkoala.koala.commons.InvokeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;

import com.dhcc.DRGsHosp.application.DrgCommonApplication;
import com.dhcc.DRGsHosp.application.ICDApplication;
import com.dhcc.DRGsHosp.application.SumExpenseApplication;
import com.dhcc.DRGsHosp.facade.ICDFacade;
import com.dhcc.DRGsHosp.infra.util.Arith;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @title :ICDFacadeImpl.java
 * @description :
 * @author :lileizheng
 * @date :2015年8月12日
 * @version :1.0
 * @copyright :DHCC 2013-2014
 */
@Named("drgsHospFacadeImpl2420181023")
public class ICDFacadeImpl implements ICDFacade {
	
	private static final Logger logger = LoggerFactory.getLogger(ICDFacadeImpl.class);

	@Autowired
	ICDApplication icdApplication;
	
	@Autowired
	private  SumExpenseApplication sumExpenseApplication;
	
	@Autowired
	DrgCommonApplication drgCommonApplication;
	
    @Autowired  
    private JdbcTemplateObj jdbcTemplateObj;
	
	 private int totalCnt=0; 
	 private int nowCnt=0; 
	 
	 private int updateCnt=0; 
	 private int insertCnt=0; 
	 private int errorCnt =0;
	 private String endStr="1";
	 
	/**
	 * 
	 * @Description：：ICD自动对照
	 * @Author LiuHongJun
	 * @see com.dhcc.DRGsHosp.facade.ICDFacade#matchICD(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public InvokeResult matchICD(String icdVersion, String userCode,
			String icdType) {
		try {
			// 加入日志
			int updates = icdApplication.matchICD(icdVersion, icdType);
			Map<String, Object> json = new HashMap<>();
			json.put("userCode", userCode);
			json.put("editType", "1");
			json.put("updates", updates);
			json.put("icdType", icdType);
			json.put("icdVersion", icdVersion);
			icdApplication.editLog(json);
			return InvokeResult.success(updates);
		} catch (Exception e) {
			return InvokeResult.failure(e.getMessage());
		}
	}

	/**
	 * @Description：获取对照结果
	 * @Author LiuHongJun
	 * @see com.dhcc.DRGsHosp.facade.ICDFacade#getICDMatchResult(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public InvokeResult getICDMatchResult(String icdVersion, String icdType,
			String depCode) {
		Map<String, Object> resultMap = new HashMap<>();
		List<Object[]> list = icdApplication
				.getICDMatchResult(icdType, depCode, icdVersion);
		List<Map<String, Object>> resultList = new LinkedList<>();
		Map<String, Object> markMap = new HashMap<>();
		// 获取北京ICD的数量
		int bjICDs = icdApplication.getBJICDCount(icdVersion, icdType);
		markMap.put("bjICDs", bjICDs);
		Map<String, Object> map = new HashMap<>();
		if (icdType.equals("O")) {
			map.put("ddesc", "全院ICD手术匹配数");
		} else {
			map.put("ddesc", "全院ICD诊断匹配数");
		}
		resultList.add(map);
		map = new HashMap<>();
		map.put("ddesc", "完全匹配数");
		resultList.add(map);
		map = new HashMap<>();
		map.put("ddesc", "ICD编码相同，描述不同");
		resultList.add(map);
		map = new HashMap<>();
		map.put("ddesc", "ICD编码不同，描述相同");
		resultList.add(map);
		map = new HashMap<>();
		map.put("ddesc", "ICD编码不同，描述不同");
		resultList.add(map);
		if (list.size() > 0) {
			double icdTotals = 0;
			Object[] objs = list.get(0);
			for (int i = 0; i < objs.length; i++) {
				Object obj = objs[i];
				resultList.get(i).put("value", obj);
				if (i == 0) {
					icdTotals = obj != null ? Double
							.parseDouble(obj.toString()) : 0;
					resultList.get(i).put("percent", 100);
				} else {
					double icds = obj != null ? Double.parseDouble(obj
							.toString()) : 0;
					double percent = icdTotals != 0 ? Arith.round(icds
							/ icdTotals * 100, 2) : 0;
					resultList.get(i).put("percent", percent);
				}
				if (i == 1) {
					double icds = obj != null ? Double.parseDouble(obj
							.toString()) : 0;
					double notMatchICDs = bjICDs - icds;
					markMap.put("notMatchICDs", notMatchICDs);
					double percent = bjICDs != 0 ? Arith.round(notMatchICDs
							/ bjICDs * 100, 2) : 0;
					markMap.put("notMatchICDPercent", percent);
				}
			}
		}
		resultMap.put("tableData", resultList);
		resultMap.put("markData", markMap);
		return InvokeResult.success(resultMap);
	}

	/**
	 * 根据传入的相关信息，返回对应的ICD对照结果
	 */
	public InvokeResult getICDMatching(Map<String, Object> param) {
		List<Map<String, Object>> resultList = icdApplication.getICDMatching(param);
		return InvokeResult.success(resultList);
	}
	
	@Override
	public Object getBJICD(String icdType, String icdVersion, String icdValue,
			String icdValue1) {
		String[] values = icdValue.split("-");
		List<Map<String, Object>> resultList = new LinkedList<>();
		List<Object[]> list = icdApplication.getBJICD(icdType, icdVersion,
				values[0], icdValue1);
		if(StringUtils.hasLength(icdValue1)){
			for (Object[] objs : list) {
				Map<String, Object> map = new HashMap<>();
				map.put("bjICDCode", objs[0]);
				map.put("bjICDDesc", objs[1]);
				map.put("group", "以下数据来源于手动搜索");
				resultList.add(map);
			}
			return resultList;
		}
		for (Object[] objs : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("bjICDCode", objs[0]);
			map.put("bjICDDesc", objs[1]);
			map.put("group", "以下数据来源于类目匹配");
			resultList.add(map);
		}
		List<String> descList = new LinkedList<>();
		descList.add(values[1]);
		Map<String,Object> paramMap=new HashMap<>();
		if("D".equals(icdType)){
			paramMap.put("dbname", "zhenduan");
		}else{
			paramMap.put("dbname", "shoushu");
		}
		String sources[]={"BJ"};
		paramMap.put("source", sources);
		paramMap.put("diag", descList.toArray());
		paramMap.put("size", 3);
		//调用API
		ObjectMapper objectMapper = new ObjectMapper();
		StringBuilder sb = new StringBuilder();
		try {
			String ICDMatchAPI=GlobalData.sysConfig.get("ICDMatchAPI");
			String ICDMatchAPIUrl="";
			if(StringUtils.hasLength(ICDMatchAPI)&&(ICDMatchAPI.split("θ").length>=2)){
				String[] ICDMatchAPIArray=ICDMatchAPI.split("θ");
				ICDMatchAPIUrl="http://"+ICDMatchAPIArray[0]+"/"+ICDMatchAPIArray[1];
			}
			
			String json=objectMapper.writeValueAsString(paramMap);
			/*********************调用接口*****************************/
			URL url = new URL(ICDMatchAPIUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			con.setRequestProperty("Accept", "application/json");
			con.setRequestMethod("POST");

			OutputStream os = con.getOutputStream();
			os.write(json.getBytes("UTF-8"));
			os.flush();
			os.close();
			int HttpResult = con.getResponseCode();
			if (HttpResult == HttpURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
			} else {
				System.out.println(con.getResponseMessage());
			}
			//解析结果
			Map<String, Object> contrastResultMap=objectMapper.readValue(sb.toString(), Map.class);
			Object contrastResult=contrastResultMap.get(values[1]);
			if(!"".equals(contrastResult)){
				List<List<Object>> contrastResultArray=(List)contrastResult;
				for(List<Object> listTemp:contrastResultArray){
					Map<String,Object> mapTemp=new HashMap<>();
//					mapTemp.put("code", values[0]);
//					mapTemp.put("desc", values[1]);
					mapTemp.put("bjICDCode", listTemp.get(1));
					mapTemp.put("bjICDDesc", listTemp.get(1)+" "+listTemp.get(0));
//					mapTemp.put("similarity", listTemp.get(2));
					mapTemp.put("group", "以下数据来源于标注系统");
					resultList.add(mapTemp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public InvokeResult updateICDMatching(Map<String, Object> json) {
		try {
			icdApplication.updateICDMatching(json);
			icdApplication.editLog(json);
		} catch (Exception e) {
			return InvokeResult.failure(e.getMessage());
		}
		return InvokeResult.success();
	}

	@Override
	public InvokeResult getEditLog(String hICDCode, String icdVersion) {
		List<Map<String, Object>> resultList = icdApplication.getEditLog(hICDCode, icdVersion);
		return InvokeResult.success(resultList);
	}

	@Override
	public InvokeResult icdImport(String icdType, Map<String, Object> param) {
		try {
			icdApplication.importICDMatching(icdType,param);
			//icdApplication.updateIsOper();
			icdApplication.editLog(param);
		} catch (Exception e) {
			return InvokeResult.failure(e.getMessage());
		}
		return InvokeResult.success();
	}
/**
 *  @Description：统计对照结果
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.facade.ICDFacade#getICDMatchResultTable(java.lang.String, java.lang.String)
 */
	@Override
	public InvokeResult getICDMatchResultTable(String icdType,String isOnlyMatch) {
		//分组器版本号
		String groupVersion = GlobalData.sysConfig.get("GROUP_VER");
		String icdVerCode=drgCommonApplication.getIcdVerCodeByGroupVersion(groupVersion);
		String [] icd=icdVerCode.split(",");
		//诊断编码版本
		String icdDiaVerConfig = icd[1]+"";
		//手术操作版本
		String icdOperVerConfig =icd[0]+"";
		List<Map<String, Object>> resultList = null;
		if("0".equals(isOnlyMatch)) {
			if ("D".equals(icdType)) {
				String sql=" select distinct hospdia.pd0101 as \"ICDCODE\",hospdia.pd0100 as \"ICDDESC\",dia.bj_icd_code as \"BJICDCODE\",dia.bj_icd_desc as \"BJICDDESC\" from drgs.mr_diagnose hospdia \r\n" + 
							"left join drgs.t_icdmatch_result_dia dia  on hospdia.pd0101=dia.hosp_icd_code and dia.drg_icd_version='"+icdDiaVerConfig+"' and dia.icdmat_type in ('0','1')\r\n" + 
							"where dia.bj_icd_code is not null and hospdia.pd0101 is not null order by  hospdia.pd0101 desc";
				resultList = jdbcTemplateObj.queryForList(sql);
				System.out.println("== icdType:"+icdType+ " == sql:"+sql);
			} else {
				String sql="select distinct hospoper.po0101 AS \"ICDCODE\",hospoper.po0100 AS \"ICDDESC\",oper.bj_icd_code as \"BJICDCODE\",oper.bj_icd_desc AS  \"BJICDDESC\" from drgs.mr_operation hospoper  \r\n" + 
						"left join drgs.t_icdmatch_result_oper oper  on hospoper.po0101=oper.hosp_icd_code and oper.drg_icd_version='"+icdOperVerConfig+"' and oper.icdmat_type in ('0','1')\r\n" + 
						"where oper.bj_icd_code is not null and hospoper.po0101 is not null order by hospoper.po0101 desc";
				resultList = jdbcTemplateObj.queryForList(sql);
				System.out.println("== icdType:"+icdType+ " == sql:"+sql);
			}

		}else {
			if ("D".equals(icdType)) {
				String sql="select  hospdia.pd0101 as \"ICDCODE\",hospdia.pd0100 as \"ICDDESC\",count(1) as \"caseCnt\" from drgs.mr_diagnose hospdia \r\n" + 
						"where not exists(\r\n" + 
						"  select dia.hosp_icd_code from drgs.t_icdmatch_result_dia dia \r\n" + 
						"  where dia.drg_icd_version='"+icdDiaVerConfig+"' and dia.icdmat_type in ('0','1')  and hospdia.pd0101=dia.hosp_icd_code\r\n" + 
						" )\r\n" + 
						" group by hospdia.pd0101,hospdia.pd0100\r\n" + 
						" order by count(1) desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			} else {
				String sql=" select distinct hospoper.po0101 as \"ICDCODE\",hospoper.po0100 as \"ICDDESC\",count(1) \"caseCnt\" from drgs.mr_operation hospoper  \r\n" + 
						"  where not exists(\r\n" + 
						"   select oper.hosp_icd_code  from drgs.t_icdmatch_result_oper oper \r\n" + 
						"   where oper.drg_icd_version='"+icdOperVerConfig+"' and oper.icdmat_type in ('1','0') and hospoper.po0101=oper.hosp_icd_code\r\n" + 
						" )\r\n" + 
						" group by hospoper.po0101,hospoper.po0100\r\n" + 
						" order by count(1) desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			}
		}
		return InvokeResult.success(resultList);
	}

	/**
	 * @methodname    :getICDMatchResultTablePlatform
	 * @description   :ICD对照平台页面数据
	 * @author        :qiaoyilong
	 * @date          :2018年11月16日
	 */
	@Override
	public InvokeResult getICDMatchResultTablePlatform(String icdType,String icdVersion, String isOnlyMatch){

		List<Map<String, Object>> resultList = null;
		if("0".equals(isOnlyMatch)) {
			if ("D".equals(icdType)) {
				String sql=" select distinct hospdia.pd0101 as \"ICDCODE\",hospdia.pd0100 as \"ICDDESC\",dia.bj_icd_code as \"BJICDCODE\",dia.bj_icd_desc as \"BJICDDESC\" from drgs.mr_diagnose hospdia \r\n" + 
							"left join drgs.t_icdmatch_result_dia dia  on hospdia.pd0101=dia.hosp_icd_code and dia.drg_icd_version='"+icdVersion+"' and dia.icdmat_type in ('0','1')\r\n" + 
							"where dia.bj_icd_code is not null and hospdia.pd0101 is not null order by  hospdia.pd0101 desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			} else {
				String sql="select distinct hospoper.po0101 AS \"ICDCODE\",hospoper.po0100 AS \"ICDDESC\",oper.bj_icd_code as \"BJICDCODE\",oper.bj_icd_desc AS  \"BJICDDESC\" from drgs.mr_operation hospoper  \r\n" + 
						"left join drgs.t_icdmatch_result_oper oper  on hospoper.po0101=oper.hosp_icd_code and oper.drg_icd_version='"+icdVersion+"' and oper.icdmat_type in ('0','1')\r\n" + 
						"where oper.bj_icd_code is not null and hospoper.po0101 is not null order by hospoper.po0101 desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			}

		}else {
			if ("D".equals(icdType)) {
				String sql="select  hospdia.pd0101 as \"ICDCODE\",hospdia.pd0100 as \"ICDDESC\",count(1) as \"caseCnt\" from drgs.mr_diagnose hospdia \r\n" + 
						"where not exists(\r\n" + 
						"  select dia.hosp_icd_code from drgs.t_icdmatch_result_dia dia \r\n" + 
						"  where dia.drg_icd_version='"+icdVersion+"' and dia.icdmat_type in ('0','1')  and hospdia.pd0101=dia.hosp_icd_code\r\n" + 
						" )\r\n" + 
						" group by hospdia.pd0101,hospdia.pd0100\r\n" + 
						" order by count(1) desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			} else {
				String sql=" select distinct hospoper.po0101 as \"ICDCODE\",hospoper.po0100 as \"ICDDESC\",count(1) \"caseCnt\" from drgs.mr_operation hospoper  \r\n" + 
						"  where not exists(\r\n" + 
						"   select oper.hosp_icd_code  from drgs.t_icdmatch_result_oper oper \r\n" + 
						"   where oper.drg_icd_version='"+icdVersion+"' and oper.icdmat_type in ('1','0') and hospoper.po0101=oper.hosp_icd_code\r\n" + 
						" )\r\n" + 
						" group by hospoper.po0101,hospoper.po0100\r\n" + 
						" order by count(1) desc";
				resultList = jdbcTemplateObj.queryForList(sql);
			}
		}
		return InvokeResult.success(resultList);		
	}

	/**
	 * @description :ICD对照文件解析
	 * @author :yujiaolong
	 * @date :2017年5月12日
	 */
	@Override
	public InvokeResult analysisICD(String icdType,String icdVersion,String userCode, String filePath) {
		totalCnt=1; 
		nowCnt=0;  
		updateCnt=0; 
	    insertCnt=0; 
		errorCnt=0;
		endStr="1";
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		if (".xls".equals(extension) || ".xlsx".equals(extension)) {
			try {
				Workbook workbook = null;
				Sheet sheet = null;
				Row row = null;
				Cell cell = null;
				if (extension.equals(".xls")) {
					try {
						workbook = new HSSFWorkbook(new FileInputStream(
								filePath));
						sheet = (HSSFSheet) workbook.getSheetAt(0);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else if (extension.equals(".xlsx")) {
					try {
						workbook = new XSSFWorkbook(new FileInputStream(
								filePath));
						sheet = (XSSFSheet) workbook.getSheetAt(0);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					System.err.println("上传的文件不是有效的excel文件！");
				}
				int rowCnt = sheet.getLastRowNum();// 总行数
				totalCnt=rowCnt;
				// 循环每一行
				for (int j = 1; j <= rowCnt; j++) {
					// 存放一行数据
					Map<String, Object> map = new HashMap<>();
					map.put("icdVersion", icdVersion);
					row = sheet.getRow(j);
					// 医院ICD编码
					cell = row.getCell(0);
					if (cell != null) {
						if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
							map.put("hICDCode", cell.getStringCellValue());
						} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							map.put("hICDCode", cell.getNumericCellValue());
						}
					}
					// 医院
					cell = row.getCell(1);
					if (cell != null) {
						cell.setCellType(cell.CELL_TYPE_STRING);
						map.put("hICDDesc", cell.getStringCellValue());
					}

					// BJ-V6.01编码
					cell = row.getCell(2);
					if (cell != null) {
						if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
							map.put("bjICDCode", cell.getStringCellValue());
						} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							map.put("bjICDCode", cell.getNumericCellValue());
						}
					}
					// BJ-V6.01描述
					cell = row.getCell(3);
					if (cell != null) {
						cell.setCellType(cell.CELL_TYPE_STRING);
						map.put("bjICDDesc", cell.getStringCellValue());
					}
					if (!map.isEmpty() && map.get("hICDCode") != null
							&& map.get("bjICDCode") != null) {
						Map<String, Integer> dmap=icdApplication.importICDMatching(icdType,map);
						if(dmap.get("editType")==1){
							map.put("userCode", userCode);
							map.put("icdType", icdType);
							map.put("editType", dmap.get("editType").toString());
							map.put("updates", dmap.get("insertCnt").toString());//保存日志时用到
							icdApplication.editLog(map);
						}else if(dmap.get("editType")==2){
							map.put("userCode", userCode);
							map.put("icdType", icdType);
							map.put("editType", dmap.get("editType").toString());
							map.put("updates", dmap.get("updateCnt").toString());
							icdApplication.editLog(map);
						}
						updateCnt=updateCnt+ Double.valueOf(dmap.get("updateCnt").toString()).intValue(); 
						insertCnt=insertCnt+ Double.valueOf(dmap.get("insertCnt").toString()).intValue(); 
						
					} else {
						// 将错误信息写入text文件
						ObjectMapper mapper = new ObjectMapper();
						String json = mapper.writeValueAsString(map);
						logger.error(json);
						errorCnt++;
					}
					nowCnt++;
				}
				//数据插入成功后更新手术/操作字段
				if("O".equals(icdType)){
					icdApplication.updateIsOper(icdVersion);
					icdApplication.updateOperation(icdVersion);
				}
				/**
				 * 读取完数据以后删除upload下的所有文件
				 */
				File tempFile = new File(filePath);
				File[] tempList = tempFile.listFiles();
				if (tempFile.isFile()) {
					tempFile.delete();
				} else {
					for (int i = 0; i < tempList.length; i++) {
						tempList[i].delete();
					}
				}

			} catch (Exception e) {
				endStr="0";
				e.printStackTrace();
				return InvokeResult.failure("");
			}
		}
		return InvokeResult.success();
	}
	/**
	 * @description :ICD对照文件解析(ICD对照平台页面用）
	 * @author :qiaoyilong
	 * @date :2018年11月17日
	 */
	@Override
	public InvokeResult analysisICDPlatform(String icdType,String icdVersion,String userCode, String filePath) {
		totalCnt=1; 
		nowCnt=0;  
		updateCnt=0; 
	    insertCnt=0; 
		errorCnt=0;
		endStr="1";
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		if (".xls".equals(extension) || ".xlsx".equals(extension)) {
			try {
				Workbook workbook = null;
				Sheet sheet = null;
				Row row = null;
				Cell cell = null;
				if (extension.equals(".xls")) {
					try {
						workbook = new HSSFWorkbook(new FileInputStream(
								filePath));
						sheet = (HSSFSheet) workbook.getSheetAt(0);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else if (extension.equals(".xlsx")) {
					try {
						workbook = new XSSFWorkbook(new FileInputStream(
								filePath));
						sheet = (XSSFSheet) workbook.getSheetAt(0);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					System.err.println("上传的文件不是有效的excel文件！");
				}
				int rowCnt = sheet.getLastRowNum();// 总行数
				totalCnt=rowCnt;
				// 循环每一行
				for (int j = 1; j <= rowCnt; j++) {
					// 存放一行数据
					Map<String, Object> map = new HashMap<>();
					map.put("icdVersion", icdVersion);
					row = sheet.getRow(j);
					// 医院ICD编码
					cell = row.getCell(0);
					if (cell != null) {
						if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
							map.put("hICDCode", cell.getStringCellValue());
						} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							map.put("hICDCode", cell.getNumericCellValue());
						}
					}
					// 医院
					cell = row.getCell(1);
					if (cell != null) {
						cell.setCellType(cell.CELL_TYPE_STRING);
						map.put("hICDDesc", cell.getStringCellValue());
					}

					// BJ-V6.01编码
					cell = row.getCell(2);
					if (cell != null) {
						if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
							map.put("bjICDCode", cell.getStringCellValue());
						} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							map.put("bjICDCode", cell.getNumericCellValue());
						}
					}
					// BJ-V6.01描述
					cell = row.getCell(3);
					if (cell != null) {
						cell.setCellType(cell.CELL_TYPE_STRING);
						map.put("bjICDDesc", cell.getStringCellValue());
					}
					if (!map.isEmpty() && map.get("hICDCode") != null && map.get("bjICDCode") != null) {
						Map<String, Integer> dmap=icdApplication.importICDMatchingPlatform(icdType,map);
						if(dmap.get("editType")==1){
							map.put("userCode", userCode);
							map.put("icdType", icdType);
							map.put("editType", dmap.get("editType").toString());
							map.put("updates", dmap.get("insertCnt").toString());//保存日志时用到
							icdApplication.editLog(map);
						}else if(dmap.get("editType")==2){
							map.put("userCode", userCode);
							map.put("icdType", icdType);
							map.put("editType", dmap.get("editType").toString());
							map.put("updates", dmap.get("updateCnt").toString());
							icdApplication.editLog(map);
						}
						updateCnt=updateCnt+ Double.valueOf(dmap.get("updateCnt").toString()).intValue(); 
						insertCnt=insertCnt+ Double.valueOf(dmap.get("insertCnt").toString()).intValue(); 
						
					} else {
						// 将错误信息写入text文件
						ObjectMapper mapper = new ObjectMapper();
						String json = mapper.writeValueAsString(map);
						logger.error(json);
						errorCnt++;
					}
					nowCnt++;
				}
				//数据插入成功后更新手术/操作字段
				if("O".equals(icdType)){
					icdApplication.updateIsOper(icdVersion);
					icdApplication.updateOperation(icdVersion);
				}
				/**
				 * 读取完数据以后删除upload下的所有文件
				 */
				File tempFile = new File(filePath);
				File[] tempList = tempFile.listFiles();
				if (tempFile.isFile()) {
					tempFile.delete();
				} else {
					for (int i = 0; i < tempList.length; i++) {
						tempList[i].delete();
					}
				}

			} catch (Exception e) {
				endStr="0";
				e.printStackTrace();
				return InvokeResult.failure("");
			}
		}
		return InvokeResult.success();
	}
	/**
	 * @param Map
	 *            <String, Object>
	 * @Description : 一条ICD的增加或者修改
	 * @return InvokeResult
	 */
	@Override
	public InvokeResult updateOneICD(Map<String, Object> dto) {
		if (dto.get("hICDCode").toString() == null
				|| dto.get("hICDCode").toString().trim() == "") {
			return InvokeResult.failure("医院ICD不能为空，更新失败");
		}
		if (dto.get("bjICDCode").toString() == null
				|| dto.get("bjICDCode").toString().trim() == "") {
			return InvokeResult.failure("北京ICD不能为空，更新失败");
		}
		try{
			Map<String,Integer> map=icdApplication.importICDMatching(dto.get("icdType").toString(), dto);
			if(map.get("editType")!=0){
				dto.put("editType", map.get("editType").toString());
				icdApplication.editLog(dto);
			}
			if("O".equals(dto.get("icdType").toString())){
				icdApplication.updateIsOperOne(dto);	
			}
			return InvokeResult.success();
		}catch(Exception e){
			e.printStackTrace();
			return InvokeResult.failure(e.toString());
		}
	}
	/**
	 * @methodname    :updateOneICDPlatform
	 * @description   : 一条ICD的增加或者修改(以hosp_icd_code + drg_icd_version为唯一判断条件）对照平台用
	 * @author        :qiaoyilong
	 * @date          :2018年11月16日
	 */
	@Override
	public InvokeResult updateOneICDPlatform(Map<String, Object> dto) {
		if (dto.get("hICDCode").toString() == null
				|| dto.get("hICDCode").toString().trim() == "") {
			return InvokeResult.failure("医院ICD不能为空，更新失败");
		}
		if (dto.get("bjICDCode").toString() == null
				|| dto.get("bjICDCode").toString().trim() == "") {
			return InvokeResult.failure("北京ICD不能为空，更新失败");
		}
		try{
			Map<String,Integer> map=icdApplication.importICDMatchingPlatform(dto.get("icdType").toString(), dto);
			if(map.get("editType")!=0){
				dto.put("editType", map.get("editType").toString());
				icdApplication.editLog(dto);
			}
			if("O".equals(dto.get("icdType").toString())){
				icdApplication.updateIsOperOne(dto);	
			}
			return InvokeResult.success();
		}catch(Exception e){
			e.printStackTrace();
			return InvokeResult.failure(e.toString());
		}
	}
	/**
	 * 
	 * @Description：根据编码获取描述
	 * @Author LiuHongJun
	 * @see com.dhcc.DRGsHosp.facade.ICDFacade#findDescByCode(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public InvokeResult findDescByCode(String code, String type) {
		return InvokeResult.success(icdApplication.findDescByCode(code, type));
	}

	/**
	 * 
	 * @Description：根据BJ编码获取描述
	 * @Author LiuHongJun
	 * @see com.dhcc.DRGsHosp.facade.ICDFacade#findBJDescByCode(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public InvokeResult findBJDescByCode(String code, String type, String icdVersion) {
		return InvokeResult.success(icdApplication.findBJDescByCode(code, type, icdVersion));
	}
/**
 *  @Description：获取导入进度
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.ICDFacade#findUploadProgress()
 */
	@Override
	public InvokeResult findUploadProgress() {
		Map<String,Object> map =new HashMap<>();
		int percent=Double.valueOf((float)nowCnt*100/(float)totalCnt).intValue();
		if(nowCnt>=totalCnt){
			percent=100;
			map.put("totalCnt", totalCnt);
			map.put("errorCnt", errorCnt);
			map.put("updateCnt", updateCnt);
			map.put("insertCnt", insertCnt);
			map.put("endStr", endStr);
		}
		map.put("percent", percent);
		return InvokeResult.success(map);
	}
/**
 * 
 *  @Description：ICD对照批量提交
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.ICDFacade#batchSummitIcd(java.lang.String, java.util.Map)
 */
@Override
public InvokeResult batchSummitIcd(String icdType, String matchType, String icdVersion) {
	try{
		icdApplication.batchSummitIcd(icdType, matchType, icdVersion);
		return InvokeResult.success();
	}catch(Exception e){
		return InvokeResult.failure(e.toString());
	}
}
/**
 *  @Description：获取北京icd
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.ICDFacade#findBjIcdCode(java.lang.String, java.lang.String)
 */
@Override
public InvokeResult findBjIcdCode(String icdVersion, String icdType) {
	return InvokeResult.success(icdApplication.findBjIcdCode(icdVersion, icdType));
}

	/**
	 * 	@Discription：定时任务调用转接，以QuartzJob结尾
	 *  @Author QiaoYiLong  
	 *  @Date: 2018年10月26日 9:21:07  
	 *  @param 默认格式为 0_0
	 *  cron 表达式  0 0 6 * * ?  每天凌晨六点整更新前一天的手术/操作
	 */
	public void updateMrIsOperQuartzJob(String param) {
		if(null != param && !"".equals(param) && param.split("_").length >= 2){
			String datas[] = param.split("_");
			String dateFrom = datas[0];
			String dateTo = datas[1];
			updateMrIsOper(dateFrom, dateTo);
		}
	}
	
	/**
	 * 
	 *  @Description：更新手术表中的手术/操作字段
	 *  @Author ZouYiyu  
	 *  @see com.dhcc.DRGsHosp.facade.ICDFacade#updateMrIsOper(java.lang.String, java.lang.String)
	 */
	@Override
	public void updateMrIsOper(String dateFrom, String dateTo) {
		if (!"0".equals(dateFrom) && !"0".equals(dateTo)) {
			dateFrom = DrgsIndex.formateDateFrom(dateFrom);
			dateTo = DrgsIndex.formateDateTo(dateTo);
			List<Map<String, Object>> listmap = sumExpenseApplication.findMrParid(dateFrom, dateTo);
			String operIcd = icdApplication.getOperIcd();
			if (!listmap.isEmpty()) {
				for (Map<String, Object> map : listmap) {
					String pMainIndex = map.get("ID") == null ? "" : map.get("ID").toString();
					icdApplication.updateMrIsOper(pMainIndex, operIcd);
				}
			}
			return;
		}else{
			//定时任务自动更新
			dateFrom = DrgsIndex.formateDateFrom(dateFrom);
			dateTo = DrgsIndex.formateDateTo(dateTo);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			date = calendar.getTime();
			dateFrom = sdf.format(date);
			dateTo = sdf.format(date);
	        //定时任务使用java反射时必须重新实例化该接口，bean括号里面填impl实例上面的@Name括号里面的内容
	        if(sumExpenseApplication==null){
	        	sumExpenseApplication =(SumExpenseApplication) ContextLoader.getCurrentWebApplicationContext().getBean("sumExpenseApplicationImplqiaoyilong20181026");
	        }
			List<Map<String, Object>> listmap = sumExpenseApplication.findMrParid(dateFrom, dateTo);
	        //定时任务使用java反射时必须重新实例化该接口，bean括号里面填impl实例上面的@Name括号里面的内容
	        if(icdApplication==null){
	        	icdApplication =(ICDApplication) ContextLoader.getCurrentWebApplicationContext().getBean("icdApplicationImplqiaoyilong20181026");
	        }
			String operIcd = icdApplication.getOperIcd();
			if (!listmap.isEmpty()) {
				for (Map<String, Object> map : listmap) {
					String pMainIndex = map.get("ID") == null ? "" : map.get("ID").toString();
					icdApplication.updateMrIsOper(pMainIndex, operIcd);
				}
			}			
		}
	}

	/**
	 * 查询数据库中icd字典版本 @Description：
	 * 
	 * @Author ZouYiyu
	 * @see com.dhcc.DRGsHosp.facade.ICDFacade#operDicType(java.lang.String)
	 */
	@Override
	public List<Map<String, Object>> operDicType(String icdType) {
		return icdApplication.operDicType(icdType);
	}

	@Override
	public InvokeResult ICDMatchBigData(String filePath,String contrastType,String contrastVersion,String contrastResultCnt) {
		StringBuffer message = new StringBuffer();//返回前台的信息
		//文件解析
		Sheet sheet=ExcelUtil.readExcelSheet(filePath,0);
		if(sheet==null){
			message.append("文件解析错误，请确认文件类型正确！<br>"); 
			return InvokeResult.failure(message.toString());
		}
		String ICDMatchAPI=GlobalData.sysConfig.get("ICDMatchAPI");
		String ICDMatchAPIUrl="";
		if(StringUtils.hasLength(ICDMatchAPI)&&(ICDMatchAPI.split("θ").length>=2)){
			String[] ICDMatchAPIArray=ICDMatchAPI.split("θ");
			ICDMatchAPIUrl="http://"+ICDMatchAPIArray[0]+"/"+ICDMatchAPIArray[1];
		}
		else{
			message.append("ICD智能匹配API地址配置错误，请到“设置>系统配置管理>接口信息”中确认接口信息！<br>"); 
			return InvokeResult.failure(message.toString());
		}
		int rowNum=sheet.getLastRowNum();//行数
		int errorRow = 0;
		Row row = null ;
		// 存放文件的表头位置
		Map<String,Object> titlemap = new HashMap<>();
		// 标题行
		Row headrow = sheet.getRow(0);
		int headCount = headrow.getLastCellNum();
		Cell cell=null;
		for (int i = 0; i < headCount; i++) {
			cell = headrow.getCell((short) i);
			titlemap.put(cell.getStringCellValue(), i);
		}
		List<String> descList=new ArrayList<>();
		List<Map<String,String>> contrastList=new ArrayList<>();
		List<Map<String,Object>> resultList=new ArrayList<>();
		//解析每一行数据
		try {
			message.setLength(0);
			for(int i = 1 ; i <= rowNum ; i++) {
				errorRow = i;
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(null == row) {
					continue ;
				}
				cell = row.getCell((int) (titlemap.get("编码") != null ? titlemap.get("编码"):1000));
				String code=ExcelUtil.getCellValue(cell);
				cell = row.getCell((int) (titlemap.get("描述") != null ? titlemap.get("描述"):1000));
				String desc=ExcelUtil.getCellValue(cell);
				if(code!=null&&desc!=null){
					Map<String,String> temp=new HashMap<>();
					temp.put("code", code);
					temp.put("desc", desc);
					contrastList.add(temp);
					descList.add(desc);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.append("第" + (errorRow) +"行数据导入时报错，导入终止。<br>"); 
			return InvokeResult.failure(message.toString());
		}finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		//判断是否有数据
		if(!(contrastList.size()>0)){
			message.append("文件中无数据，请确认！<br>"); 
			return InvokeResult.failure(message.toString());
		}
		
		//调用API-拼接参数
		ObjectMapper objectMapper = new ObjectMapper();
		StringBuilder sb = new StringBuilder();
		String json="";
		Map<String,Object> paramMap=new HashMap<>();
		String sources[]={contrastVersion};
		paramMap.put("source", sources);
		paramMap.put("diag", descList.toArray());
		paramMap.put("size", contrastResultCnt);
		paramMap.put("dbname", contrastType);
		//调用API
		try {
			json=objectMapper.writeValueAsString(paramMap);
			/*********************调用接口*****************************/
			URL url = new URL(ICDMatchAPIUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			con.setRequestProperty("Accept", "application/json");
			con.setRequestMethod("POST");

			OutputStream os = con.getOutputStream();
			os.write(json.getBytes("UTF-8"));
			os.flush();
			os.close();
			int HttpResult = con.getResponseCode();
			if (HttpResult == HttpURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
			} else {
				message.append("调用接口出错，请确认！"); 
				System.out.println(con.getResponseMessage());
				return InvokeResult.failure(message.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.append("调用接口出错，请确认！"); 
			return InvokeResult.failure(message.toString());
		}
		
		//解析结果
		try {
			@SuppressWarnings("rawtypes")
			Map contrastResultMap=objectMapper.readValue(sb.toString(), Map.class);
			for(Map<String,String> tempContrast:contrastList){
				String codeHospital=tempContrast.get("code");
				String descHospital=tempContrast.get("desc");
				Object contrastResult=contrastResultMap.get(descHospital);
				if(!"".equals(contrastResult)){
					@SuppressWarnings("unchecked")
					List<List<Object>> contrastResultArray=(ArrayList)contrastResult;
					for(List<Object> listTemp:contrastResultArray){
						Map<String,Object> mapTemp=new HashMap<>();
						mapTemp.put("code", codeHospital);
						mapTemp.put("desc", descHospital);
						mapTemp.put("toCode", listTemp.get(1));
						mapTemp.put("toDesc", listTemp.get(0));
						mapTemp.put("similarity", listTemp.get(2));
						resultList.add(mapTemp);
					}
				}
				else{
					continue;
				}
			}
			return InvokeResult.success(resultList);
		} catch (Exception e) {
			e.printStackTrace();
			message.append("解析结果错误！"); 
			return InvokeResult.failure(message.toString());
		}
	}

	@Override
	public List<Map<String, Object>> getNoCompareCase(String icdCode,String icdDesc ,String icdType) {
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		result = icdApplication.getNoCompareCase(icdCode,icdDesc,icdType);
		System.out.println(result);
		return result;
	}

	@Override
	public List<Map<String, Object>> findDiags(String condition) {
		return icdApplication.findDiags(condition);
	}

	@Override
	public List<Map<String, Object>> findOpers(String condition) {
		return icdApplication.findOpers(condition);
	}
}
